package governor

import (
	"context"
	"log"
	"net"
	"net/http"

	"gitee.com/zawei/yggdrasil/pkg/transport"
	"gitee.com/zawei/yggdrasil/pkg/transport/server"
	"gitee.com/zawei/yggdrasil/pkg/utils/xnet"
)

// Server ...
type Server struct {
	*http.Server
	listener net.Listener
	*Config
	info *server.Info
}

func newServer(config *Config) *Server {
	var listener, err = net.Listen("tcp4", config.Address())
	if err != nil {
		log.Fatalf("governor start error: %s", err.Error())
	}
	config.Host, config.Port = xnet.GetHostAndPortByAddr(listener.Addr())
	info := server.NewInfo(
		server.WithScheme("governor"),
		server.WithAddress(config.Host, config.Port),
		server.WithKind(transport.ServiceGovernor),
	)
	return &Server{
		Server: &http.Server{
			Addr:    config.Address(),
			Handler: DefaultServeMux,
		},
		listener: listener,
		Config:   config,
		info:     &info,
	}
}

//Serve ..
func (s *Server) Start() error {
	err := s.Server.Serve(s.listener)
	if err == http.ErrServerClosed {
		return nil
	}
	return err

}

func (s *Server) Init() error {
	return nil
}

//Stop ..
func (s *Server) Stop() error {
	return s.Server.Close()
}

//GracefulStop ..
func (s *Server) GracefulStop(ctx context.Context) error {
	return s.Server.Shutdown(ctx)
}

//Info ..
func (s *Server) Info() *server.Info {
	return s.info
}
